package utils;

import bean.Order;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class OrderIO {
    //创建订单列表
    private List<Order> orderList = new ArrayList<>();
    //保存订单对象的文件名常量
    private static final String ORDER_FILE = "order.obj";

    //添加订单
    public void add(Order order) throws BusinessException {
        orderList.add(order);
        //writeOrders();
    }
    //返回订单列表
    public List<Order> list() throws BusinessException {
        //readOrders();
        return orderList;
    }
    //查找订单
    public Order findByOrderId(int orderId) throws BusinessException {
        Order order = null;
        int oid;//临时变量
        for (Order o : orderList) {
            oid = o.getOrderId();
            if (oid == orderId) {
                order = o;
                break;
            }
        }
        return order;
    }
    //写入订单列表
    public boolean writeOrders() {
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(ORDER_FILE));
            out.writeObject(orderList);
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    //读取订单列表
    public boolean readOrders() {
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(ORDER_FILE));
            orderList = ((List<Order>) in.readObject());
            in.close();
            return true;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }
}
